require(["config"], function() {
    require(["jquery","template", "zoom", "cookie","load" ], function($,template) {
        
        function List(){
            this.loadIndex();
            this.addListener();
            $.cookie.json = true;
        }
        
        $.extend(List.prototype,{
            //加载渲染列表商品
            loadIndex(){
                const _id = location.search.slice(location.search.lastIndexOf("=")+1);
                // console.log(_id)
                $.getJSON("http://rap2api.taobao.org/app/mock/120970/api/detail?id="+_id,(data)=>{
                    // console.log(data)
                    const {title,price,price2,img,id,zoomImgs} = data.res_body;
                   const html = template("prod-temp-detail",{"id":id,"zoomImgs":zoomImgs,"title":title , "price":price , "price2":price2 , "img":img ,})
                  
                   $(".detail_wrap").append(html);
                   
                   $(".zoom-img").elevateZoom({
                    gallery:'gal1',
                    cursor: 'pointer',
                    galleryActiveClass: 'active'
                }); 
                });
            },
            addListener(){
                $(".detail_wrap").on("click" ,"#btn_cart,#btn_cart2" , this.addToCart)
            },
            
            //添加到购物车
            addToCart(){
                const $parent = $(".detail_right");
                const currentProduct = {
                    id:$parent.find(".id").text(),
                    title:$parent.find(".title").text(),
                    price:$parent.find(".price").text(),
                    price2:$parent.find(".price2").text(),
                    img:$parent.find(".img").attr("src"),
                    amount:1
                };
                console.log(currentProduct)

                //获取在cookie中已保存的购物车数组
                const cart = $.cookie("cart") || [];
                // 判断在 cart 数组中是否存在当前选购的商品对象
                const has = cart.some(curr=>{
                    if (curr.id == currentProduct.id) { // 已有选购
						curr.amount++; // 增加数量
						return true;
					}
					return false;
                });
                //如果未选购过
                if(!has)
                    cart.push(currentProduct);
                    // 将购物车的数组保存到 cookie 中
                    $.cookie("cart",cart,{expires:10, path:"/"});



                return false;
            }
        });
        new List();






        //放大镜
        
    });
});